﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wenku8.Exceptions;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Web.Http;
using Windows.Web.Http.Filters;

namespace wenku8.Parser
{
    public class HTMLParser
    {
        private static HttpClient httpClientInstance;

        public static async Task<bool> InitializeAsync()
        {
            var appData = ApplicationData.Current.LocalSettings;
            if (!appData.Values.ContainsKey("UserName") || appData.Values["UserName"] == null) {
                throw new UserNotExists();
            }
            else {
                var password = appData.Values["Password"] as string;
                var userName = appData.Values["UserName"] as string;
                return await SetHttpClientInstanceAsync(userName, password);
            }
        }

        /// <summary>
        /// 初始化 httpClientInstanceAsync
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        private static async Task<bool> SetHttpClientInstanceAsync(string userName, string password)
        {
            httpClientInstance = new HttpClient();// new HttpBaseProtocolFilter() { AutomaticDecompression = true }
            httpClientInstance.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36");
            httpClientInstance.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8;charset=gbk");
            httpClientInstance.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
            httpClientInstance.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
            //httpClientInstance.DefaultRequestHeaders.Add("Referer", "https://www.wenku8.net/login.php?jumpurl=http%3A%2F%2Fwww.wenku8.net%2Findex.php");
            httpClientInstance.DefaultRequestHeaders.Add("Host", "www.wenku8.net");
            httpClientInstance.DefaultRequestHeaders.Add("Connection", "keep-alive");
            httpClientInstance.DefaultRequestHeaders.Add("Origin", "https://www.wenku8.net");
            httpClientInstance.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");

            var uri = new Uri("https://www.wenku8.net/login.php?do=submit&jumpurl=http%3A%2F%2Fwww.wenku8.net%2Findex.php");
            var httpResponse = new HttpResponseMessage();
            try {
                // 表单数据
                var paramList = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("username", userName),
                    new KeyValuePair<string, string>("password", password),
                    new KeyValuePair<string, string>("usecookie", "0"),
                    new KeyValuePair<string, string>("action", "login"),
                    new KeyValuePair<string, string>("submit", "%26%23160%3B%B5%C7%26%23160%3B%26%23160%3B%C2%BC%26%23160%3B"),
                    new KeyValuePair<string, string>("Content-Type", "application/x-www-form-urlencoded;charset=GBK")
                };
                var content = new HttpFormUrlEncodedContent(paramList);
                httpResponse = await httpClientInstance.PostAsync(uri, content);
                httpResponse.EnsureSuccessStatusCode();
                return true;
            }
            catch {
                return false;
            }
        }

        /// <summary>
        /// 获取目标URI的HTML源码
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> GetHtmlString(string url)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding gbk = Encoding.GetEncoding("GBK");
            Encoding iso8859_1 = Encoding.GetEncoding("ISO-8859-1");
            try {
                var httpResponseBody = await httpClientInstance.GetAsync(new Uri(url));
                var content = await httpResponseBody.Content.ReadAsStringAsync();
                byte[] bytesu16 = iso8859_1.GetBytes(content);
                return gbk.GetString(bytesu16);
            }
            catch (Exception) {
            }
            return null;
        }

        public static void Dispose()
        {
            httpClientInstance?.Dispose();
        }

        public static async Task<string> PostMessage(Uri uri, List<KeyValuePair<string, string>> parameters)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding gbk = Encoding.GetEncoding("GBK");
            Encoding iso8859_1 = Encoding.GetEncoding("ISO-8859-1");
            try {
                var httpResponseBody = await httpClientInstance.PostAsync(uri, new HttpFormUrlEncodedContent(parameters));
                var content = await httpResponseBody.Content.ReadAsStringAsync();
                byte[] bytesu16 = iso8859_1.GetBytes(content);
                return gbk.GetString(bytesu16);
            }
            catch (Exception) {

            }
            return null;
        }
    }
}
